﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using Code4WP7SDK;
using Newtonsoft.Json;
using LuWeibo.Models;
using LuWeiboSDK;
using System.IO;

namespace LuWeibo
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string access_token = (string)IsoStorageHelper.GetValueFromSettings("access_token");
            if (string.IsNullOrEmpty(access_token))
            {
                GoToLoginPage();
            }
            else
            {
                Constant.AccessToken = access_token;
                GetUid();
            }
            base.OnNavigatedTo(e);
        }

        private void LoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
        }

        private void LoginBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            string codeUrl = string.Concat(Constant.RedirectUrl, "/", Constant.Mark, Constant.CodeResponseType);
            if (e.Uri.AbsoluteUri.Contains(codeUrl))
            {
                //e.Cancel = true;
                List<Parameter> parameters = ParameterHelper.GetParametersFromUrl(e.Uri.AbsoluteUri);
                string data = string.Format
                    ("client_id={0}&client_secret={1}&grant_type={2}&redirect_uri={3}&code={4}", Constant.Appkey, Constant.AppSecret, Constant.TokenResponseType, Constant.RedirectUrl, parameters[0].Value);
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += ws_WebClientCompleted;
                ws.PostRequest(Constant.AccessTokenUrl, data);
            }
            
        }

        void ws_WebClientCompleted(object sender, WebClientCompletedEventArgs e)
        {
            if (e.Ex == null)
            {
                //Debug.WriteLine(e.Result.ToString());
                AccessTokenModel tokenModel = JsonConvert.DeserializeObject<AccessTokenModel>(e.Result.ToString());
                //写入静态变量中
                Constant.AccessToken = tokenModel.access_token;
                if (IsoStorageHelper.GetValueFromSettings("access_token") != null) 
                {
                    IsoStorageHelper.DeleteSettings("access_token");
                }
                IsoStorageHelper.SaveInToSettings("access_token", Constant.AccessToken);
                //string cookie = this.GetCookie(); -- //TODO 这里后去cookie清除之后重新登录但是似乎能获取无法删除
                GetUid();
            }
            else
            {
                //TODO 异常处理
            }
        }


        //获取用户编号
        private void GetUid()
        {
            string data = ParameterHelper.BuildParameters(new List<Parameter>());
            WebClientService ws = new WebClientService();
            ws.WebClientCompleted += (s, e) =>
            {
                if (e.Ex == null)
                {
                    string uIdJson = e.Result.ToString();
                    int maoIndex = uIdJson.IndexOf(":");
                    string uid = uIdJson.Replace("{", "").Replace("}", "").Substring(maoIndex);
                    Constant.UID = uid;
                    NavigateToLuHomePage();
                }
                else
                {
                    GoToLoginPage();
                }
            };
            ws.GetRequest(Urls.account_get_uid, data);
            //获取用户编号
            //List<Parameter> paras = new List<Parameter>();
            //paras.Add(new Parameter("screen_name","动点飞扬"));
            //string data1 = ParameterHelper.BuildParameters(paras);
            //ws.WebClientCompleted += (s, e) =>
            //    {
            //        Debug.WriteLine(e.Result.ToString());
            //    };
            //ws.GetRequest(Urls.users_show, data1);
        }
        /// <summary>
        /// 跳转到卤微博首页
        /// </summary>
        private void NavigateToLuHomePage()
        {
            this.NavigationService.Navigate(new Uri("/Views/LuHomePage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// 跳转到登录页
        /// </summary>
        private void GoToLoginPage()
        {
            string loginUrl = string.Format("{0}{1}client_id={2}&response_type={3}&redirect_uri={4}&display={5}",
                Constant.AuthorizeUrl, Constant.Mark, Constant.Appkey, Constant.CodeResponseType, Constant.RedirectUrl, Constant.DisplayType);
            LoginBrowser.Navigate(new Uri(loginUrl, UriKind.Absolute));
        }
 
        private void LoginBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoginBrowser.InvokeScript("eval",
                @"
                window.ScanTelTag=function(elem) {
                if (elem.getAttribute('target') != null && elem.getAttribute('target').indexOf('_parent') == 0) {
                    elem.setAttribute('target', '_self');
                    }
                }
            
                window.Initialize=function() {
                var elems = document.getElementsByTagName('a');
                for (var i = 0; i < elems.length; i++)
                ScanTelTag(elems[i]);
                }");
                LoginBrowser.InvokeScript("Initialize");
            }
            catch (Exception)
            {

            }
        }

        //private string GetCookie()
        //{
        //    object obj = LoginBrowser.InvokeScript("eval", "document.cookie");
        //    if (obj is string)
        //    {
        //        string strCookie = obj as string;
        //        return strCookie;
        //    }
        //    return null;
        //}

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            App app = Application.Current as App;
            app.Exit();
        }
    }
}